<template>
  <span @click.stop="sendCode" class="sendcode" v-loading="isSend" element-loading-spinner="el-icon-loading">{{text}}</span>
</template>
<script>
export default {
  name: 'sendCode',
  props: {
    ajax: {
      required: true,
      type: Function
    },
    data: {
      default: () => { },
      type: Object,
      required: false
    }
  },
  computed: {
    //   是禁用
    disabled() {
      return this.currentTime != 60 || this.isSend
    },
    text() {
      if (this.disabled) {
        return this.currentTime + 's'
      } else {
        return '发送验证码'
      }
    },
  },
  data() {
    return {
      currentTime: 60,
      isSend: false,
      timeBox: undefined
    }
  },
  methods: {
    sendCode() {
      if (this.disabled) return;
      this.isSend = true
      this.ajax(this.data).then(() => {
        this.countdown()
        this.$message.success('发送成功')
      }).finally(() => {
        this.isSend = false
      })
    },
    countdown() {
      this.currentTime--
      this.timeBox = setInterval(() => {
        if (this.currentTime === 0) {
          this.currentTime = 60
          clearInterval(this.timeBox)
        } else {
          this.currentTime--
        }
      }, 1000)
    }
  }
}
</script>
<style scoped>
.sendcode {
  cursor: pointer;
}
.sendcode /deep/ .el-loading-spinner{
    margin-top: -9px;
}
</style>
